import { useState, useEffect } from "react";
import { View, Image, Text, Button } from "@tarojs/components";
import { useRouter } from "@tarojs/taro";
import Taro from "@tarojs/taro";
import { get, post } from "../../../axios/aiaxios/request";
import { API_BASE_URL } from "../../../../config/env";
import { formatLocalDateTime } from "../../../utils/aidateFormat";
import "./TensorFlow.scss";

// 辅助函数：自动清理临时缓存文件
const autoCleanCache = async (): Promise<void> => {
  try {
    console.log("🧹 开始自动清理临时缓存文件...");
    const fs = Taro.getFileSystemManager();
    const userDataPath = Taro.env.USER_DATA_PATH;
    
    if (!userDataPath) {
      console.warn("⚠️ 无法获取用户数据路径，跳过清理");
      return;
    }

    fs.readdir({
      dirPath: userDataPath,
      success: (res) => {
        let cleanedCount = 0;
        res.files.forEach(file => {
          if (file.startsWith('temp_analysis_')) {
            try {
              fs.unlinkSync(`${userDataPath}/${file}`);
              cleanedCount++;
              console.log('🗑️ 已删除临时文件:', file);
            } catch (e) {
              console.warn('删除文件失败:', file, e);
            }
          }
        });
        if (cleanedCount > 0) {
          console.log(`✅ 自动清理完成，删除了 ${cleanedCount} 个临时文件`);
        } else {
          console.log("📝 没有找到需要清理的临时文件");
        }
      },
      fail: (error) => {
        console.warn('读取缓存目录失败:', error);
      }
    });
  } catch (error) {
    console.error('自动清理缓存失败:', error);
  }
};

// 辅助函数：保存分析结果到数据库
const saveAnalysisResult = async (imageId: string, analysisData: any): Promise<void> => {
  try {
    console.log("💾 开始保存分析结果到数据库...");
    console.log("📊 保存数据:", {
      imageId,
      faceCount: analysisData.faceCount,
      hasAiAnalysis: !!analysisData.aiAnalysis
    });

    const response = await post('/aisave/save', {
      imageId: imageId,
      analysisData: analysisData
    });

    console.log("💾 保存响应:", response);

    if (response?.code === 200) {
      console.log("✅ 分析结果保存成功，保存ID:", response.data._id);
    } else {
      console.warn("⚠️ 保存分析结果失败:", response?.message || "未知错误");
      // 即使保存失败也不影响用户体验，只记录日志
    }
  } catch (error) {
    console.error("❌ 保存分析结果异常:", error);
    // 保存失败不影响用户的分析流程，只记录错误
  }
};

// 辅助函数：处理base64图片，检查大小限制并优化
const handleBase64Image = async (base64Data: string): Promise<string> => {
  console.log("📄 开始处理base64图片数据");
  
  // 获取base64数据（移除前缀）
  const base64String = base64Data.split(",")[1] || base64Data;
  const base64Size = base64String.length;
  const fileSizeInMB = (base64Size * 3) / 4 / (1024 * 1024); // base64转换为字节大小的近似值
  
  console.log(`📊 Base64数据大小: ${base64Size} 字符 (约 ${fileSizeInMB.toFixed(2)} MB)`);
  
  // 微信小程序本地存储限制通常是10MB，我们设置8MB为安全限制
  const MAX_SIZE_MB = 8;
  
  if (fileSizeInMB > MAX_SIZE_MB) {
    console.warn(`⚠️ 图片过大 (${fileSizeInMB.toFixed(2)} MB > ${MAX_SIZE_MB} MB)，尝试使用网络URL代替`);
    throw new Error(`图片过大 (${fileSizeInMB.toFixed(2)} MB)，建议使用网络图片或压缩后上传`);
  }
  
  try {
    // 使用文件系统管理器写入临时文件
    const fs = Taro.getFileSystemManager();
    const userDataPath = Taro.env.USER_DATA_PATH;
    
    if (!userDataPath) {
      throw new Error("无法获取用户数据路径");
    }
    
    const tempFilePath = `${userDataPath}/temp_analysis_${Date.now()}.jpg`;
    
    console.log("📁 尝试写入临时文件:", tempFilePath);
    
    try {
      fs.writeFileSync(tempFilePath, base64String, "base64");
      console.log("✅ Base64临时文件保存成功:", tempFilePath);
      return tempFilePath;
    } catch (writeError) {
      // 如果写入失败可能是因为存储空间不足
      if (writeError.message.includes("storage limit") || writeError.message.includes("exceed")) {
        console.warn("⚠️ 存储限制错误，建议清理缓存");
        throw new Error("存储空间不足，请清理小程序缓存后重试");
      }
      throw writeError;
    }
  } catch (error) {
    console.error("❌ Base64文件保存失败:", error);
    throw new Error(`保存临时文件失败: ${error.message}`);
  }
};

export default function TensorFlow() {
  const router = useRouter();
  const [apiData, setApiData] = useState<any>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [errorMsg, setErrorMsg] = useState<string>("");
  const [isAnalyzing, setIsAnalyzing] = useState(false);
  const [analysisResult, setAnalysisResult] = useState<any>(null);
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [showFaceScan, setShowFaceScan] = useState(false);
  const [imageLoadFailed, setImageLoadFailed] = useState(false);

  const imageId = router.params.imageId;

  const loadImage = async () => {
    try {
      console.log('🔄 开始加载图片数据...');
      console.log('📋 图片ID:', imageId);
      console.log('🌐 API地址:', API_BASE_URL);
      
      const response = await get(`/aiimg/getById?id=${imageId}`);
      console.log('📥 服务器响应:', response);

      if (response?.code === 200 && response?.data) {
        console.log('✅ 图片数据获取成功');
        console.log('📊 图片数据详情:', {
          id: response.data._id,
          name: response.data.name,
          img: response.data.img,
          hasBase64: !!response.data.base64,
          base64Length: response.data.base64?.length || 0,
          uploadTime: response.data.uploadTime
        });
        
        setApiData(response.data);
        setIsLoading(false);
        setErrorMsg("");
      } else {
        console.error('❌ 服务器返回错误:', response);
        setErrorMsg("获取图片失败");
        setIsLoading(false);
      }
    } catch (error) {
      console.error("❌ 网络请求失败:", error);
      console.error("🔍 错误详情:", {
        message: error?.message,
        stack: error?.stack,
        name: error?.name
      });
      setErrorMsg("网络请求失败");
      setIsLoading(false);
    }
  };

  // 面部分析函数
  const analyzeFace = async () => {
    if (!apiData) {
      Taro.showToast({
        title: "请先加载图片",
        icon: "error",
      });
      return;
    }

    setIsAnalyzing(true);
    setIsFullscreen(true); // 开始分析时进入全屏模式
    
    // 延迟显示人脸扫描动画，等待图片放大动画完成
    setTimeout(() => {
      setShowFaceScan(true);
    }, 500);
    
    console.log("🚀 开始面部分析流程");
    console.log("📸 图片信息:", {
      id: apiData._id,
      name: apiData.name,
      img: apiData.img,
      uploadTime: apiData.uploadTime,
    });

    try {
      // 不显示原生的loading，使用我们的动画效果
      // Taro.showLoading({
      //   title: "正在分析中...",
      // });

      // 优化图片处理流程，避免文件存储限制
      let tempFilePath = "";

      // 优先使用网络URL，避免创建大的临时文件
      if (apiData.img) {
        console.log("🌐 使用网络URL下载图片到临时文件");
        const imageUrl = `${API_BASE_URL}${apiData.img}`;
        console.log("📍 图片URL:", imageUrl);

        try {
          const downloadResult = await Taro.downloadFile({
            url: imageUrl,
          });

          if (downloadResult.statusCode === 200) {
            tempFilePath = downloadResult.tempFilePath;
            console.log("📁 图片下载完成:", tempFilePath);
          } else {
            throw new Error(`下载失败，状态码: ${downloadResult.statusCode}`);
          }
        } catch (downloadError) {
          console.warn("⚠️ 网络下载失败，尝试使用base64:", downloadError.message);
          
          // 如果网络下载失败，再尝试base64方式（但要注意大小限制）
          if (apiData.base64) {
            tempFilePath = await handleBase64Image(apiData.base64);
          } else {
            throw new Error("无法获取图片数据");
          }
        }
      } else if (apiData.base64) {
        // 只有在没有网络URL时才使用base64
        tempFilePath = await handleBase64Image(apiData.base64);
      } else {
        throw new Error("没有找到图片数据");
      }

      console.log("📦 准备上传的文件路径:", tempFilePath);
      console.log("📤 开始上传到面部分析接口");

      // 调用面部分析接口
      const uploadResult = await Taro.uploadFile({
        url: `${API_BASE_URL}/aiimg/analyzeFace`,
        filePath: tempFilePath,
        name: "photo",
        formData: {
          name: `面部分析-${apiData.name}`,
        },
        header: {
          "Content-Type": "multipart/form-data",
        },
      });

      console.log("📥 上传响应状态:", uploadResult.statusCode);
      // console.log('📄 原始响应数据:', uploadResult.data)

      if (uploadResult.statusCode === 200) {
        const response = JSON.parse(uploadResult.data);
        console.log("✅ 解析后的响应:", response);
        // console.log('📝 完整响应结构:', JSON.stringify(response, null, 2))

        if (response.code === 200) {
          // 根据实际返回的数据结构，分析数据在response.data.analysis中
          const responseData = response.data;
          const analysisData = responseData.analysis;

          console.log("🔍 开始处理分析数据...");
          console.log("- response.data:", responseData);
          console.log("- analysis对象:", analysisData);
          
          // 检查analysisData是否存在再获取其键
          if (analysisData && typeof analysisData === 'object') {
          console.log("- analysis对象的键:", Object.keys(analysisData));
          } else {
            console.log("- analysis对象为空或不是对象");
          }

          // 检查分析是否成功
          if (!analysisData || !analysisData.success) {
            console.log("⚠️ 分析未成功，可能原因:");
            console.log("- 分析状态:", analysisData?.success);
            console.log("- 检测到的人脸数量:", analysisData?.faceCount);
            
            // 分析失败时也要恢复原样
            setShowFaceScan(false);
            setTimeout(() => {
              setIsFullscreen(false);
            }, 300);

            Taro.showToast({
              title: analysisData?.faceCount === 0 ? "未检测到人脸" : "分析失败",
              icon: "none",
            });
            return;
          }

          console.log("🎯 面部分析详细数据:");
          console.log("=".repeat(60));
          console.log("📊 分析结果概览:");
          console.log("- 分析状态:", analysisData.success ? "成功" : "失败");
          console.log("- 检测到的人脸数量:", analysisData.faceCount);
          
          // 安全地访问imageInfo
          if (analysisData.imageInfo) {
          console.log(
            "- 图片尺寸:",
            `${analysisData.imageInfo.width} × ${analysisData.imageInfo.height}`
          );
          }
          
          if (analysisData.timestamp) {
          console.log("- 分析时间:", analysisData.timestamp);
          }

          if (analysisData.faces && analysisData.faces.length > 0) {
            analysisData.faces.forEach((face, index) => {
              console.log(`\n👤 人脸 ${index + 1} 详细分析数据:`);
              console.log("-".repeat(40));
              console.log("📍 检测信息:");
              console.log(
                "  - 置信度:",
                (face.confidence * 100).toFixed(1) + "%"
              );
              console.log(
                "  - 位置:",
                `(${face.boundingBox.x}, ${face.boundingBox.y})`
              );
              console.log(
                "  - 尺寸:",
                `${face.boundingBox.width} × ${face.boundingBox.height}`
              );

              // 性别和年龄信息
              if (face.gender) {
                console.log("👫 性别分析:");
                console.log(
                  "  - 性别:",
                  face.gender.gender === "male" ? "男性" : "女性"
                );
                console.log("  - 置信度:", face.gender.probability + "%");
              }

              if (face.age) {
                console.log("📅 年龄分析:");
                console.log("  - 估计年龄:", face.age.age + "岁");
                console.log("  - 年龄范围:", face.age.ageRange);
              }

              console.log("😊 表情分析:");
              console.log("  - 主要表情:", face.expressions.dominant);
              console.log("  - 表情置信度:", face.expressions.confidence + "%");
              console.log("  - 所有表情分数:", face.expressions.scores);

              console.log("👁️ 面部特征:");
              console.log("  - 脸型:", face.features.faceShape);
              console.log("  - 眼距:", face.features.eyeDistance + "px");
              console.log("  - 鼻长:", face.features.noseLength + "px");
              console.log("  - 嘴宽:", face.features.mouthWidth + "px");
              console.log(
                "  - 面部比例 (高/宽):",
                face.features.faceDimensions.ratio
              );

              console.log("📏 比例分析:");
              console.log(
                "  - 三庭平衡:",
                face.proportions.threeCourtAnalysis.isBalanced
                  ? "均衡"
                  : "不均衡"
              );
                              console.log(
                  "  - 三眼平衡:",
                  face.proportions.threeEyeAnalysis.isBalanced ? "均衡" : "不均衡"
                );

              // 黄金比例分析结果
              if (face.goldenRatio) {
                console.log("🏛️ 黄金比例分析:");
                console.log(`  - 综合得分: ${face.goldenRatio.totalScore}/100`);
                console.log(`  - 评级: ${face.goldenRatio.grade}`);
                
                if (face.goldenRatio.details) {
                  console.log("  📊 各维度得分:");
                  
                  if (face.goldenRatio.details.threeCourts) {
                    console.log(`    1. 三庭比例: ${face.goldenRatio.details.threeCourts.score}/100 (${face.goldenRatio.details.threeCourts.analysis})`);
                    console.log(`       上庭:${face.goldenRatio.details.threeCourts.upperRatio}% | 中庭:${face.goldenRatio.details.threeCourts.middleRatio}% | 下庭:${face.goldenRatio.details.threeCourts.lowerRatio}%`);
                  }
                  
                  if (face.goldenRatio.details.threeEyes) {
                    console.log(`🔍 前端收到的三眼数据检查:`);
                    console.log(`    analysis: ${face.goldenRatio.details.threeEyes.analysis}`);
                    console.log(`    leftEyeRatio原始值: ${face.goldenRatio.details.threeEyes.leftEyeRatio}`);
                    console.log(`    eyeGapRatio原始值: ${face.goldenRatio.details.threeEyes.eyeGapRatio}`);
                    console.log(`    rightEyeRatio原始值: ${face.goldenRatio.details.threeEyes.rightEyeRatio}`);
                    console.log(`    2. 三眼比例: ${face.goldenRatio.details.threeEyes.score}/100 (${face.goldenRatio.details.threeEyes.analysis})`);
                    console.log(`       左眼:${(face.goldenRatio.details.threeEyes.leftEyeRatio*100).toFixed(1)}% | 眼距:${(face.goldenRatio.details.threeEyes.eyeGapRatio*100).toFixed(1)}% | 右眼:${(face.goldenRatio.details.threeEyes.rightEyeRatio*100).toFixed(1)}%`);
                    if (face.goldenRatio.details.threeEyes.analysis.includes('修改版')) {
                      console.log(`✅ 确认：前端收到了修改后的数据!`);
                    } else {
                      console.log(`❌ 警告：前端可能收到的是旧数据!`);
                    }
                  }
                  
                  if (face.goldenRatio.details.faceRatio) {
                    console.log(`    3. 面部总体: ${face.goldenRatio.details.faceRatio.score}/100 (${face.goldenRatio.details.faceRatio.analysis})`);
                    console.log(`       公式: ${face.goldenRatio.details.faceRatio.formula || '脸长 ÷ 脸宽'}`);
                    console.log(`       脸长:${face.goldenRatio.details.faceRatio.faceLength}px | 脸宽:${face.goldenRatio.details.faceRatio.faceWidth}px`);
                    console.log(`       实际比例:${face.goldenRatio.details.faceRatio.actualRatio} | 黄金比例:${face.goldenRatio.details.faceRatio.goldenRatio} | 偏差:${face.goldenRatio.details.faceRatio.deviation}`);
                  }
                  
                  if (face.goldenRatio.details.noseMouthRelation) {
                    console.log(`    4. 鼻嘴关系: ${face.goldenRatio.details.noseMouthRelation.score}/100 (${face.goldenRatio.details.noseMouthRelation.analysis})`);
                    console.log(`       实际比例:${face.goldenRatio.details.noseMouthRelation.actualRatio} | 理想比例:${face.goldenRatio.details.noseMouthRelation.idealRatio}`);
                  }
                  
                  if (face.goldenRatio.details.noseMouthWidth) {
                    console.log(`    5. 鼻嘴宽度: ${face.goldenRatio.details.noseMouthWidth.score}/100 (${face.goldenRatio.details.noseMouthWidth.analysis})`);
                    console.log(`       实际比例:${face.goldenRatio.details.noseMouthWidth.actualRatio} | 理想比例:${face.goldenRatio.details.noseMouthWidth.idealRatio}`);
                    console.log(`       鼻翼宽度:${face.goldenRatio.details.noseMouthWidth.noseWidth}px | 嘴巴宽度:${face.goldenRatio.details.noseMouthWidth.mouthWidth}px`);
                  }
                  
                  if (face.goldenRatio.details.eyebrowPosition) {
                    console.log(`    6. 眉毛位置: ${face.goldenRatio.details.eyebrowPosition.score}/100 (${face.goldenRatio.details.eyebrowPosition.analysis})`);
                    console.log(`       眉眼比例:${face.goldenRatio.details.eyebrowPosition.eyebrowEyeRatio} | 对称度:${face.goldenRatio.details.eyebrowPosition.symmetry}%`);
                  }
                }
                
                if (face.goldenRatio.summary) {
                  if (face.goldenRatio.summary.strengths && face.goldenRatio.summary.strengths.length > 0) {
                    console.log("  ✨ 优势特征:", face.goldenRatio.summary.strengths.join(", "));
                  }
                  if (face.goldenRatio.summary.improvements && face.goldenRatio.summary.improvements.length > 0) {
                    console.log("  📈 可优化方面:", face.goldenRatio.summary.improvements.join(", "));
                  }
                }
              } else {
                console.log("⚠️ 未收到黄金比例分析数据");
              }

              console.log("💄 美容建议:");
              face.beautifyRecommendations.forEach((rec, i) => {
                console.log(
                  `  ${i + 1}. [${rec.type}] ${rec.suggestion} (置信度: ${
                    rec.confidence
                  }%)`
                );
              });


            });
          } else {
            console.log("⚠️ 没有检测到人脸数据");
          }
          console.log("=".repeat(60));

          console.log('🔥🔥🔥 DEBUGGING: 这里应该显示AI分析检查! 🔥🔥🔥');
          
          // 显示AI分析结果
          console.log("🚀 即将检查AI分析结果...");
          console.log("🔍 检查AI分析结果:");
          console.log("- analysisData类型:", typeof analysisData);
          console.log(
            "- analysisData.aiAnalysis存在:",
            !!analysisData.aiAnalysis
          );
          console.log(
            "- analysisData.aiAnalysis类型:",
            typeof analysisData.aiAnalysis
          );

          if (analysisData.aiAnalysis) {
            console.log("\n🤖 =============== AI智能分析结果 ===============");
            console.log("AI分析结果：", analysisData.aiAnalysis);
            console.log("🤖 ==========================================\n");
          } else {
            console.log("\n⚠️ 未收到AI分析结果，可能AI服务未启动或出现错误");
            console.log(
              "📋 完整响应数据结构:",
              JSON.stringify(response, null, 2)
            );
          }

          // 设置分析结果，保持原有的数据结构
          setAnalysisResult(responseData);

          // 保存分析结果到数据库
          await saveAnalysisResult(imageId, analysisData);

          // 分析完成后恢复原样
          setTimeout(() => {
            setShowFaceScan(false);
            setTimeout(() => {
              setIsFullscreen(false);
            }, 300);
          }, 1000); // 显示结果1秒后开始恢复

          Taro.showToast({
            title: "分析完成",
            icon: "success",
          });
        } else {
          throw new Error(response.message || "分析失败");
        }
      } else {
        throw new Error(`请求失败，状态码: ${uploadResult.statusCode}`);
      }
    } catch (error) {
      console.error("❌ 面部分析失败:", error);
      console.log("🔍 错误详情:", {
        message: error.message,
        stack: error.stack,
      });

      // 分析失败时也要恢复原样
      setShowFaceScan(false);
      setTimeout(() => {
        setIsFullscreen(false);
      }, 300);

      // 根据错误类型提供更具体的提示
      let errorMessage = "分析失败，请重试";
      if (error.message.includes("图片过大")) {
        errorMessage = "图片文件过大，请使用更小的图片";
      } else if (error.message.includes("文件存储限制")) {
        errorMessage = "存储空间不足，请清理缓存后重试";
      } else if (error.message.includes("网络")) {
        errorMessage = "网络连接异常，请检查网络后重试";
      } else if (error.message.includes("下载")) {
        errorMessage = "图片下载失败，请重试";
      }

      Taro.showToast({
        title: errorMessage,
        icon: "none",
        duration: 3000
      });
    } finally {
      setIsAnalyzing(false);
      // Taro.hideLoading(); // 不使用原生loading
      console.log("🏁 分析流程结束");
      
      // 自动清理临时缓存文件
      setTimeout(() => {
        autoCleanCache();
      }, 1000); // 延迟1秒执行清理，确保分析完全结束
    }
  };

  useEffect(() => {
    if (imageId) {
      loadImage();
    } else {
      setErrorMsg("缺少图片ID");
      setIsLoading(false);
    }
  }, [imageId]);

  if (isLoading) {
    return (
      <View className="tensorflow-container">
        <View className="loading-container">
          <Text className="loading-text">正在加载图片...</Text>
        </View>
      </View>
    );
  }

  if (errorMsg || !apiData) {
    return (
      <View className="tensorflow-container">
        <View className="error-container">
          <Text className="error-text">{errorMsg || "未找到图片"}</Text>
          <View className="action-buttons">
            <Button
              className="retry-button primary"
              onClick={() => loadImage()}
            >
              重试获取
            </Button>
            <Button
              className="retry-button secondary"
              onClick={() => Taro.navigateBack()}
            >
              返回上一页
            </Button>
          </View>
        </View>
      </View>
    );
  }

  // 构造图片URL，添加备用策略
  const getImageUrl = () => {
    // 如果apiData不存在，返回空字符串
    if (!apiData) {
      return '';
    }
    
    let url = '';
    
    // 如果之前加载失败且有base64数据，直接使用base64
    if (imageLoadFailed && apiData.base64) {
      url = apiData.base64;
      console.log('🔄 图片加载失败，切换到base64数据');
    } else if (apiData.img && !imageLoadFailed) {
      // 优先尝试服务器图片URL
      url = `${API_BASE_URL}${apiData.img}`;
      console.log('🌐 使用服务器图片URL:', url);
    } else if (apiData.base64) {
      // 备用：使用base64数据
      url = apiData.base64;
      console.log('🖼️ 使用base64图片数据');
    } else {
      console.warn('⚠️ 没有找到图片数据');
    }
    
    if (url) {
      console.log('📸 最终图片URL:', url.substring(0, 100) + (url.length > 100 ? '...' : ''));
    }
    return url;
  };

  const imageUrl = getImageUrl();

  return (
    <View className="tensorflow-container">
      {/* 全屏图片分析模式 */}
      {isFullscreen && (
        <View className={`fullscreen-overlay ${isFullscreen ? 'show' : ''}`}>
          <View className="fullscreen-image-container">
            <Image 
              src={imageUrl} 
              className="fullscreen-image" 
              mode="aspectFit"
              onError={(e) => {
                console.error('❌ 全屏图片加载失败:', e);
              }}
              onLoad={() => {
                console.log('✅ 全屏图片加载成功');
              }}
            />
            
            {/* 人脸扫描动画效果 */}
            {showFaceScan && (
              <View className="face-scan-overlay">
                {/* 扫描线动画 */}
                <View className="scan-line"></View>
                
                {/* 四角扫描框 */}
                <View className="scan-corners">
                  <View className="corner top-left"></View>
                  <View className="corner top-right"></View>
                  <View className="corner bottom-left"></View>
                  <View className="corner bottom-right"></View>
                </View>
                
                {/* 扫描提示文字 */}
                <View className="scan-text-container">
                  <Text className="scan-text">正在进行AI面部识别分析</Text>
                  <View className="loading-dots">
                    <View className="dot"></View>
                    <View className="dot"></View>
                    <View className="dot"></View>
                  </View>
                </View>
              </View>
            )}
          </View>
        </View>
      )}

      <View className="image-preview-section">
        <Image 
          src={imageUrl} 
          className="preview-image" 
          mode="aspectFit"
          onError={(e) => {
            console.error('❌ 图片加载失败:', e);
            console.error('失败的图片URL:', imageUrl);
            console.error('API_BASE_URL:', API_BASE_URL);
            console.error('apiData.img:', apiData?.img);
            
            // 如果服务器图片加载失败且有base64数据，尝试切换
            if (!imageLoadFailed && apiData?.base64) {
              console.log('🔄 尝试切换到base64图片');
              setImageLoadFailed(true);
            } else {
              Taro.showToast({
                title: '图片加载失败',
                icon: 'none',
                duration: 2000
              });
            }
          }}
          onLoad={() => {
            console.log('✅ 图片加载成功');
          }}
        />
        <View className="image-info">
          <Text className="image-name">{apiData.name}</Text>
          <Text className="upload-time">
            上传时间: {formatLocalDateTime(apiData.uploadTime)}
          </Text>
        </View>
      </View>

      <View className="analysis-section">
        <View className="section-header">
          <Text className="section-title">AI智能分析</Text>
        </View>
        <View className="analysis-content">
          {!analysisResult ? (
            <>
              <Text className="analysis-text">
                {isAnalyzing
                  ? "正在使用AI进行面部识别分析..."
                  : "点击下方按钮开始AI面部分析"}
              </Text>
              <Text className="analysis-description">
                我们的AI系统将对您的照片进行深度学习分析，
                包括面部特征识别、美学评估等多个维度。
              </Text>
            </>
          ) : null}
          {analysisResult && analysisResult.analysis && (
            <View className="analysis-results">
            <Text className="analysis-success">
                ✅ 分析完成！检测到 {analysisResult.analysis.faceCount} 张人脸
              </Text>
              
              {/* 渲染每个人脸的详细分析结果 */}
              {analysisResult.analysis.faces && analysisResult.analysis.faces.length > 0 && (
                <View className="faces-analysis">
                  {analysisResult.analysis.faces.map((face, index) => (
                    <View key={index} className="face-result">
                      <Text className="face-title">👤 人脸 {index + 1} 分析结果</Text>
                      
                      {/* 基本信息 */}
                      {/* <View className="result-section">
                        <Text className="section-title">📊 检测信息</Text>
                        <Text className="result-item">置信度: {(face.confidence * 100).toFixed(1)}%</Text>
                        <Text className="result-item">
                          人脸位置: ({face.boundingBox.x}, {face.boundingBox.y})
                        </Text>
                        <Text className="result-item">
                          照片尺寸: {face.boundingBox.width} × {face.boundingBox.height}
                        </Text>
                      </View> */}

                      {/* 性别和年龄 */}
                      {face.gender && (
                        <View className="result-section">
                          <Text className="section-title">👫 性别分析</Text>
                          <Text className="result-item">
                            性别: {face.gender.gender === "male" ? "男性" : "女性"}
                          </Text>
                          {/* <Text className="result-item">置信度: {face.gender.probability}%</Text> */}
                        </View>
                      )}

                      {face.age && (
                        <View className="result-section">
                          <Text className="section-title">📅 年龄分析</Text>
                          {/* <Text className="result-item">估计年龄: {face.age.age}岁</Text>
                          <Text className="result-item">年龄范围: {face.age.ageRange}</Text> */}
                          <Text className="result-item">估计年龄范围: {face.age.ageRange}</Text>
                        </View>
                      )}

                      {/* 表情分析 */}
                      <View className="result-section">
                        <Text className="section-title">😊 表情分析</Text>
                        <Text className="result-item">主要表情: {face.expressions.dominant}</Text>
                        {/* <Text className="result-item">表情置信度: {face.expressions.confidence}%</Text> */}
                        
                        {/* 显示所有表情分数（如果存在） */}
                        {face.expressions.scores && Object.keys(face.expressions.scores).length > 0 && (
                          <View className="expression-scores">
                            <Text className="scores-title">详细表情分析:</Text>
                            {Object.entries(face.expressions.scores).map(([expr, score], index) => (
                              <Text key={index} className="score-item">
                                {expr}: {typeof score === 'number' ? score : (Number(score) * 100).toFixed(1)}%
                              </Text>
                            ))}
                          </View>
                        )}
                      </View>

                      {/* 面部特征 */}
                      <View className="result-section">
                        <Text className="section-title">👁️ 面部特征</Text>
                        <Text className="result-item">脸型: {face.features.faceShape}</Text>
                        {/* <Text className="result-item">眼距: {face.features.eyeDistance}px</Text>
                        <Text className="result-item">鼻长: {face.features.noseLength}px</Text>
                        <Text className="result-item">嘴宽: {face.features.mouthWidth}px</Text> */}
                        {/* <Text className="result-item">
                          面部比例: {face.features.faceDimensions.ratio}
                        </Text> */}
                      </View>

                      {/* 黄金比例分析 */}
                      {face.goldenRatio && (
                        <View className="result-section golden-ratio-section">
                          <Text className="section-title">🏛️ 黄金比例分析</Text>
                          
                          {/* 总体评分 */}
                          <View className="golden-ratio-score">
                            <Text className="score-main">综合得分: {face.goldenRatio.totalScore}/100</Text>
                            <Text className="score-grade">评级: {face.goldenRatio.grade}</Text>
                          </View>
                          
                          {/* 各维度得分 */}
                          {face.goldenRatio.details && (
                            <View className="golden-ratio-details">
                              <Text className="details-title">📊 各维度分析:</Text>
                              
                              {/* 三庭比例 */}
                              {face.goldenRatio.details.threeCourts && (
                                <View className="dimension-item">
                                  <Text className="dimension-title">1. 垂直三庭 (理想1:1:1)</Text>
                                  <Text className="dimension-score">得分: {face.goldenRatio.details.threeCourts.score}/100</Text>
                                  <Text className="dimension-detail">
                                    上庭(发际线-眉间):{face.goldenRatio.details.threeCourts.upperRatio}% | 
                                    中庭(眉间-鼻底):{face.goldenRatio.details.threeCourts.middleRatio}% | 
                                    下庭(鼻底-下巴底):{face.goldenRatio.details.threeCourts.lowerRatio}%
                                  </Text>
                                  <Text className="dimension-analysis">{face.goldenRatio.details.threeCourts.analysis}</Text>
                                </View>
                              )}
                              
                              {/* 三眼比例 */}
                              {face.goldenRatio.details.threeEyes && (
                                <View className="dimension-item">
                                  <Text className="dimension-title">2. 水平三眼 (理想1:1:1)</Text>
                                  <Text className="dimension-score">得分: {face.goldenRatio.details.threeEyes.score}/100</Text>
                                  <Text className="dimension-detail">
                                    左眼:{(face.goldenRatio.details.threeEyes.leftEyeRatio*100).toFixed(1)}% | 
                                    眼距:{(face.goldenRatio.details.threeEyes.eyeGapRatio*100).toFixed(1)}% | 
                                    右眼:{(face.goldenRatio.details.threeEyes.rightEyeRatio*100).toFixed(1)}%
                                  </Text>
                                  <Text className="dimension-analysis">{face.goldenRatio.details.threeEyes.analysis}</Text>
                                </View>
                              )}
                              
                              {/* 面部总体比例 */}
                              {face.goldenRatio.details.faceRatio && (
                                <View className="dimension-item">
                                  <Text className="dimension-title">3. 面部总体比例 (黄金比例1.618)</Text>
                                  <Text className="dimension-score">得分: {face.goldenRatio.details.faceRatio.score}/100</Text>
                                  <Text className="dimension-detail">
                                    公式: {face.goldenRatio.details.faceRatio.formula || '脸长 ÷ 脸宽'}
                                  </Text>
                                  <Text className="dimension-detail">
                                    脸长: {face.goldenRatio.details.faceRatio.faceLength}px | 
                                    脸宽: {face.goldenRatio.details.faceRatio.faceWidth}px
                                  </Text>
                                  <Text className="dimension-detail">
                                    实际比例: {face.goldenRatio.details.faceRatio.actualRatio} | 
                                    黄金比例: {face.goldenRatio.details.faceRatio.goldenRatio} | 
                                    偏差: {face.goldenRatio.details.faceRatio.deviation}
                                  </Text>
                                  <Text className="dimension-analysis">{face.goldenRatio.details.faceRatio.analysis}</Text>
                                </View>
                              )}
                              
                              {/* 鼻嘴关系 */}
                              {face.goldenRatio.details.noseMouthRelation && (
                                <View className="dimension-item">
                                  <Text className="dimension-title">4. 鼻嘴位置关系 (理想1.618)</Text>
                                  <Text className="dimension-score">得分: {face.goldenRatio.details.noseMouthRelation.score}/100</Text>
                                  <Text className="dimension-detail">
                                    实际比例: {face.goldenRatio.details.noseMouthRelation.actualRatio} | 
                                    理想比例: {face.goldenRatio.details.noseMouthRelation.idealRatio}
                                  </Text>
                                  <Text className="dimension-analysis">{face.goldenRatio.details.noseMouthRelation.analysis}</Text>
                                </View>
                              )}
                              
                              {/* 鼻嘴宽度 */}
                              {face.goldenRatio.details.noseMouthWidth && (
                                <View className="dimension-item">
                                  <Text className="dimension-title">5. 鼻嘴宽度关系 (理想1.618)</Text>
                                  <Text className="dimension-score">得分: {face.goldenRatio.details.noseMouthWidth.score}/100</Text>
                                  <Text className="dimension-detail">
                                    实际比例: {face.goldenRatio.details.noseMouthWidth.actualRatio} | 
                                    理想比例: {face.goldenRatio.details.noseMouthWidth.idealRatio}
                                  </Text>
                                  <Text className="dimension-detail">
                                    鼻翼宽度: {face.goldenRatio.details.noseMouthWidth.noseWidth}px | 
                                    嘴巴宽度: {face.goldenRatio.details.noseMouthWidth.mouthWidth}px
                                  </Text>
                                  <Text className="dimension-analysis">{face.goldenRatio.details.noseMouthWidth.analysis}</Text>
                                </View>
                              )}
                              
                              {/* 眉眼比例 */}
                              {face.goldenRatio.details.eyebrowEyeRatio && (
                                <View className="dimension-item">
                                  <Text className="dimension-title">6. 眉眼比例关系</Text>
                                  <Text className="dimension-score">得分: {face.goldenRatio.details.eyebrowEyeRatio.score}/100</Text>
                                  <Text className="dimension-detail">
                                    实际比例: {face.goldenRatio.details.eyebrowEyeRatio.actualRatio} | 
                                    理想比例: {face.goldenRatio.details.eyebrowEyeRatio.idealRatio}
                                  </Text>
                                  <Text className="dimension-detail">
                                    眼长: {face.goldenRatio.details.eyebrowEyeRatio.eyeLength}px | 
                                    眉眼间距: {face.goldenRatio.details.eyebrowEyeRatio.eyebrowDistance}px
                                  </Text>
                                  <Text className="dimension-detail">
                                    对称度: {face.goldenRatio.details.eyebrowEyeRatio.symmetry}% | 
                                    偏差: {face.goldenRatio.details.eyebrowEyeRatio.deviation}
                                  </Text>
                                  <Text className="dimension-analysis">{face.goldenRatio.details.eyebrowEyeRatio.analysis}</Text>
                                </View>
                              )}
                            </View>
                          )}
                          
                          {/* 优势和改进建议 */}
                          {face.goldenRatio.summary && (
                            <View className="golden-ratio-summary">
                              {face.goldenRatio.summary.strengths && face.goldenRatio.summary.strengths.length > 0 && (
                                <View className="summary-section">
                                  <Text className="summary-title">✨ 优势特征:</Text>
                                  {face.goldenRatio.summary.strengths.map((strength, index) => (
                                    <Text key={index} className="summary-item">• {strength}</Text>
                                  ))}
                                </View>
                              )}
                              
                              {face.goldenRatio.summary.improvements && face.goldenRatio.summary.improvements.length > 0 && (
                                <View className="summary-section">
                                  <Text className="summary-title">📈 可优化方面:</Text>
                                  {face.goldenRatio.summary.improvements.map((improvement, index) => (
                                    <Text key={index} className="summary-item">• {improvement}</Text>
                                  ))}
                                </View>
                              )}
                            </View>
                          )}
                        </View>
                      )}

                      {/* 比例分析 */}
                      <View className="result-section">
                        <Text className="section-title">📏 基础比例分析</Text>
                        
                        {/* 面部长宽比 */}
                        <Text className="result-item">
                          面部长宽比: {face.proportions.faceRatio}
                        </Text>
                        {face.proportions.faceRatioGrade && (
                          <Text className="result-item">
                            长宽比评级: {face.proportions.faceRatioGrade}
                          </Text>
                        )}
                        
                        {/* 传统比例分析 */}
                        <Text className="result-item">
                          三庭平衡: {face.proportions.threeCourtAnalysis.isBalanced ? "✅均衡" : "❌不均衡"}
                        </Text>
                        <Text className="result-item">
                          三眼平衡: {face.proportions.threeEyeAnalysis.isBalanced ? "✅均衡" : "❌不均衡"}
                        </Text>
                      </View>

                      {/* 美容建议 */}
                      {face.beautifyRecommendations && face.beautifyRecommendations.length > 0 && (
                        <View className="result-section">
                          <Text className="section-title">💄 美容建议</Text>
                          {face.beautifyRecommendations.map((rec, i) => (
                            <Text key={i} className="result-item">
                              {/* {i + 1}. [{rec.type}] {rec.suggestion} (置信度: {rec.confidence}%) */}
                              {i + 1}. {rec.suggestion}
            </Text>
                          ))}
                        </View>
                      )}
                    </View>
                  ))}
                </View>
              )}

              {/* AI分析结果 */}
              {analysisResult.analysis.aiAnalysis && (
                <View className="ai-analysis-section">
                  <Text className="section-title">AI智能分析</Text>
                  <Text className="ai-analysis-text">{analysisResult.analysis.aiAnalysis}</Text>
                </View>
              )}
            </View>
          )}
        </View>
      </View>

      <View className="action-section">
        <Button
          className="action-button primary"
          onClick={analyzeFace}
          loading={isAnalyzing}
          disabled={isAnalyzing}
        >
          {isAnalyzing ? "分析中..." : analysisResult ? "重新分析" : "开始分析"}
        </Button>
        <Button
          className="action-button secondary"
          onClick={() => Taro.navigateBack()}
        >
          返回
        </Button>
      </View>
    </View>
  );
}
